//
//  HUD.swift
//  dcloudlive
//
//  Created by zhuxietong on 2020/3/18.
//  Copyright © 2020 douyun. All rights reserved.
//

import Foundation
import MBProgressHUD

private struct MoHudKey {
    static var hud = "mo_hud"
}

extension UIView{
    
    @objc public var mo_hud:HUD{
        get{
            if let obj = objc_getAssociatedObject(self, &MoHudKey.hud) as? HUD
            {
                return obj
            }
            let newValue = HUD(at: self)
            
            objc_setAssociatedObject(self, &MoHudKey.hud, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            return newValue
        }
        set{
            
            objc_setAssociatedObject(self, &MoHudKey.hud, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            
        }
    }
}





@objc public class HUD:NSObject{
    public func setAtMaiThread(block:@escaping (_:MBProgressHUD?)->Void) {
        DispatchQueue.main.async(execute: {[weak self] in
            block(self?.hud)
        })
    }
    public static let window = UIWindow()
    
    @discardableResult
    @objc public func show(tip message:String?)->HUD{
        
//        print("klasksldk====,\(String(describing: message))")
        self.tip(.message(msg: message ?? ""))
        return self.show()
        
//        case message(msg:String)
//        case error(msg:String)
//        case success(msg:String)
    }
    
    
    
    
    fileprivate static var _share:HUD? = nil
    @objc public static var share:HUD{
        get{
            if let share = _share{
                return share
            }
            let view = HUD.rootView
            if let v = view{
                let hud = HUD(at: v)
                _share = hud
                return hud
            }
            let hud = HUD()
            _share = hud
            return hud
        }
    }

    public static var _rootview:UIView? = nil

    public static var rootView:UIView?{
        get{
            var view:UIView? = UIApplication.shared.keyWindow
//            print("LLLLSLSLSLls",view)
            _rootview = view
            if view == nil{
                view = UIApplication.shared.keyWindow?.rootViewController?.view
                _rootview = view

            }
            if view == nil{
                view = __nav.view
                _rootview = view


            }
//            print(";lasd;dsaf---",view)

//            let view = window
            return view
        }
    }
    
    @objc public static var keyWindow:UIWindow? = nil
    @objc public static var topWindow:UIWindow?{
    
        if let window = keyWindow{
            return window
        }
//        if let window = UIApplication.shared.windows.first{
//            return window
//        }
//
        
        var topW = UIApplication.shared.keyWindow
        for win in UIApplication.shared.windows.reversed() {
            if let top = topW{
                if top === win{
                    continue
                }
                if (win.windowLevel > top.windowLevel) && !win.isHidden{
                    topW = win
                }
            }
            
        }
        return topW
    }
    
    

    public weak var view: UIView? = nil
    public var hud: MBProgressHUD? = nil
    @objc public init(at view:UIView?) {
        self.view = view
    }
    
    public override init() {
        self.view = HUD.rootView
    }
 
    
    @discardableResult
    public func mode(_ mode:MBProgressHUDMode)->HUD{
        setAtMaiThread { (hud) in
            hud?.mode = mode
        }
        return self
    }
    
    @discardableResult
    public func label(text:String?) -> HUD {
        setAtMaiThread { (hud) in
            hud?.label.textColor = .color(light: "#222", dark: "#fff")
            hud?.label.text = text
        }
        return self
    }
    
    @discardableResult
    public func detail(text:String?)->HUD{
        hud?.detailsLabel.text = text
        return self
    }
    
    @discardableResult
    public func offset(offset:CGPoint) -> HUD {
        setAtMaiThread { (hud) in
            hud?.offset = offset
        }
        return self
    }
    
    @discardableResult
    public func button(_ title:String,action:@escaping ()->Void) -> HUD {
//        mode(.determinate)
        buttoBlock = action

        setAtMaiThread { (hud) in
            hud?.button.setTitle(title, for: .normal)
        }
        hud?.button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

      
        return self
    }
    
    @discardableResult
    public func min(size:CGSize) -> HUD {
        hud?.minSize = size
        setAtMaiThread { (hud) in
            hud?.minSize = size
        }
        return self
    }
    
    @discardableResult
    public func content(color:UIColor) -> HUD {
        return self
    }
    
    @discardableResult
    public func custom(view:UIView) -> HUD {
        return self
    }
    
    @discardableResult
    public func progress(_ progress:Float) -> HUD {
        DispatchQueue.main.async(execute: {[weak self] in
            self?.hud?.mode = .determinateHorizontalBar
            self?.hud?.progress = progress
        })
        return self
    }
    
    @discardableResult
    @objc public func hide(animated:Bool,delay:TimeInterval=0) -> HUD {
        
        setAtMaiThread {(hud) in
            
            if delay <= 0{
                hud?.hide(animated: animated)
                
            }
            else{
                hud?.hide(animated: animated, afterDelay: delay)
            }
            
        }
        return self
    }
    
    fileprivate var buttoBlock:()->Void = {}
    @objc public func buttonAction(){
        buttoBlock()
    }

    @discardableResult
    public func show(animated:Bool=true) -> HUD {
        guard let v = view else {
            return self
        }
        
        setAtMaiThread {[weak self] (hud) in
//            if v == HUD.window{
//                HUD.window.makeKeyAndVisible()
//            }
//
//            print("::L----",v)
            var hud = MBProgressHUD.forView(v)
            if hud == nil{
                hud = MBProgressHUD.showAdded(to: v, animated: animated)
                self?.hud = hud
            }
            self?.hud?.show(animated: animated)
//            self?.hud = MBProgressHUD.showAdded(to: v, animated: animated)
        }
        
        return self
    }
    
    @discardableResult
    public func tip(_ action:Tip) ->HUD {
        setAtMaiThread {(hud) in
            switch action {
            case .success(msg: let msg):
                if let img = UIImage(named: "hud_checkmark")?.withRenderingMode(.alwaysTemplate){
                    hud?.customView = UIImageView(image: img)
                    hud?.mode = .customView
                    hud?.label.text = msg
                }
            case .error(msg: let msg):
                    hud?.mode = .text
                    hud?.label.text = msg
            case .message(msg: let msg):
                hud?.mode = .text
                hud?.label.text = msg
            }
        }
        return self
    }
    
  
    
    public enum Tip {
        case message(msg:String)
        case error(msg:String)
        case success(msg:String)
    }
    
    
    
}
